<?php
/**
* Hellos Model for Hello World Component
*
* @package Joomla.Tutorials
* @subpackage Components
* @link http://dev.joomla.org/component/option,com_jdwiki/
Itemid,31/id,tutorials:components/
* @license GNU/GPL
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
jimport( 'joomla.application.component.model' );
/**
* Hello Model
*
* @package Joomla.Tutorials
* @subpackage Components
*/
class AccessrulesModelAccessrules extends JModel {
	/**
	* Hellos data array
	*
	* @var array
	*/
	var $_data;
	
	var $_id;

	/**
	* Constructor that retrieves the ID from the request
	*
	* @access public
	* @return void
	*/
	function __construct()
	{
		parent::__construct();
		$array = JRequest::getVar('cid', 0, '', 'array');
		$this->setId((int)$array[0]);
	}
	
	/**
	* Method to set the hello identifier
	*
	* @access public
	* @param int Hello identifier
	* @return void
	*/
	function setId($id)
	{
		// Set id and wipe data
		$this->_id = $id;
		$this->_data = null;
	}
	
	/**
	* Method to store a record
	*
	* @access public
	* @return boolean True on success
	*/
	function store() {
		$row =& $this->getTable();
		$data = JRequest::get( 'post' );
		// Bind the form fields to the hello table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		// Store the web link table to the database
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}


	/**
	* Returns the query
	* @return string The query to be used to retrieve the rows from
	the database
	*/
	
	function _buildQuery()
	{
		
		$query = ' SELECT * '
		. ' FROM #__hello '
		;
		return $query;
	}
	
	function getSections () {
		$query = 'SELECT s.id, s.title '  .
				' FROM #__sections AS s ' .
				' WHERE s.published = 1 ';		
		$db	= & JFactory::getDBO();
		$db->setQuery($query);
		return ($db->loadObjectList());
	}
	
	function getCategories ($idSec = null) {
		$query = 'SELECT c.id, c.title, c.section AS idsecsion '  .
				' FROM #__categories AS c ' .
				' INNER JOIN #__sections AS s ON s.id = c.section' .
				' WHERE c.published = 1 ' .
				' AND s.published = 1';
				
		if ($idSec != null) {
			$query = $query.' AND s.id ='.(int)$idSec;
		}
		
		$db	= & JFactory::getDBO();
		$db->setQuery($query);
		return ($db->loadObjectList());
	}
	
	function getGroups () {
		$query = 'SELECT g.id, g.name'  .
				' FROM #__core_acl_aro_groups AS g '.
				' WHERE g.id > 30';//g.id > 30 means: choice all of rules which isn't in basic rule (Author, Editor, Manager, Supper Administrator, Administrator, ...)
		$db	= & JFactory::getDBO();
		$db->setQuery($query);
		return ($db->loadObjectList());
	}
	
	/**
	 * Create or Update
	 */
	function saveGroup ($idGroup = 0, $nameOfGroup) {
		try {
			$db	= & JFactory::getDBO();
			if ($idGroup == 0) {
				$query =" INSERT INTO `#__core_acl_aro_groups` (`parent_id`, `name`, `value`)".
						" VALUES ('28','".$nameOfGroup."','".$nameOfGroup."')";//Default: id = 28 means: Public Backend
			} else {
				$query =' UPDATE `#__core_acl_aro_groups`'.
						' SET `name` = "'.$nameOfGroup.'", `value` ="'.$nameOfGroup.'"'.
						' WHERE id = '.(int)$idGroup;
			}
			$db->setQuery($query);
			$db->query();
			return JText::_("UPDATE_SUCCESSFULLY");
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return $e->getMessage();
		}			
	
	}
	
	/*
	 *Delete Group
	 */
	function deleteGroup ($idGroup) {
		try {
			$db	= & JFactory::getDBO();
			$query =' DELETE FROM `#__core_acl_aro_groups`'.
					' WHERE id = '.(int)$idGroup;			
			$db->setQuery($query);
			$db->query();
			return JText::_("DELETE_SUCCESSFULLY");
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return $e->getMessage();
		}			
	
	}
	
	/*
	 *Delete User from Group
	 */
	function deleteUserFromGroup ($idUser) {
		try {
			$db	= & JFactory::getDBO();
			$query =' UPDATE `#__users`'.
					' SET `gid` = 18, './/18: means Registered Account
					' 	  `usertype` = "Registered"' .
					' WHERE id = '.(int)$idUser;
					
			$db->setQuery($query);
			$db->query();
			return JText::_("DELETE_USER_FROM_GROUP_SUCCESSFULLY");
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return $e->getMessage();
		}						
	}
	
	/**
	* Add User into Group
	*/
	function addUserIntoGroup ($idUser, $groupId, $groupName) {
		try {
			$db	= & JFactory::getDBO();
			$query =' UPDATE `#__users`'.
					' SET `gid` = '. (int) $groupId . ',' .
					' 	  `usertype` = "' . $groupName . '"' .
					' WHERE id = '.(int)$idUser;
					
			$db->setQuery($query);
			$db->query();
			return JText::_("ADD_USER_INTO_GROUP_SUCCESSFULLY");
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return $e->getMessage();
		}						
	}
	
	function getUsers () {
		$query = 'SELECT u.id, u.name, u.email '  .
				' FROM #__users AS u ' .
				' WHERE u.block = 0 ';
		$db	= & JFactory::getDBO();
		$db->setQuery($query);
		return ($db->loadObjectList());
	}
	
	/** Get Users By Group
	 * @status: TRUE means get all of users being in Group, otherwise FALSE
	 */	
	function getUsersByGroup ($groupId, $status) {
		if ($status) {//get all of users being in Group
			$query = 'SELECT u.id, u.name, u.email '  .
					' FROM #__users AS u ' .
					' WHERE u.block = 0 ' .
					' AND u.gid = '. (int)$groupId .
					' AND u.gid != 25'; //NOT BE Supper Administrator
		} else {//get all of users NOT being in Group
			$query = 'SELECT u.id, u.name, u.email '  .
					' FROM #__users AS u ' .
					' WHERE u.block = 0 ' .
					' AND u.gid != '. (int)$groupId .
					' AND u.gid != 25'; //NOT BE Supper Administrator
		}
		$db	= & JFactory::getDBO();
		$db->setQuery($query);		
		return ($db->loadObjectList());
	}
	
	/**
	* Search Content by Id Section and id Category
	* @var idSection
	& @var idCategory
	* @return list of Content
	the database
	*/
	function getContentsBySecAndCat ($idSection, $idCategory) {
		$query ='SELECT c.*, cc.title AS category_name, s.title AS section_name' .
				' FROM #__content AS c' .
				' INNER JOIN #__categories AS cc ON cc.id = c.catid' .
				' INNER JOIN #__sections AS s ON s.id = c.sectionid' .
				' WHERE cc.id = '. (int) $idCategory .
				' AND s.id = '. (int) $idSection .
				' AND c.state != -2'; //-2: trong sot rac
		$db	= & JFactory::getDBO();
		$db->setQuery($query);
		return ($db->loadObjectList());
	}
	
	/**
	* Save All in DB
	* @var arrUserType: array of User Type ID
	& @var arrContentType: array of Content Type ID
	* @var strUserType: USER or GROUP
	* @var strContenType: CONNTENT or CATEGORY
	* @var $rules: Rules
	* @return message of result
    */
	function saveAll ($arrUserType, $arrContentType, $strUserType, $strContenType, $rules) {
		try {			
			$db	= & JFactory::getDBO();
			for ($i=0; $i < count($arrUserType); $i++) {
				for ($j=0; $j < count($arrContentType); $j++)  {
					$from  =" FROM `#__access_rules`";
					$where =" WHERE `userType` = '". $strUserType. "'".
							" AND `contentType` = '". $strContenType. "'".
							" AND `idUserType` = '". $arrUserType[$i]. "'".
							" AND `idContentType` = '". $arrContentType[$j]. "'";
					
					//DELETE before INSERT
					$query = 'DELETE '.$from.$where;										
					$db->setQuery($query);
					$db->query();
					
					//INSERT
					/*$objDB = new StdClass();
					$objDB->id = null;
					$objDB->idUserType = $arrUserType[$i];
					$objDB->userType = $strUserType;
					$objDB->rules = $rules;
					$objDB->idContentType = $arrContentType[$j];
					$objDB->contentType = $strContenType;
					$db->insertObject("#__access_rules", $objDB, 'id');
					echo  $db->getQuery();*/

					$query =" INSERT INTO `#__access_rules` (`idUserType`, `userType`, `rules`, `idContentType`, `contentType`)".
							" VALUES ('".$arrUserType[$i]."','".$strUserType."','".$rules."','".$arrContentType[$j]."','".$strContenType."')";
					//echo $query;							
					$db->setQuery($query);
					$db->query();
					
	
				}
			}
			JText::_("UPDATE_SUCCESSFULLY");
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return $e->getMessage();
		}
	}
	
	/**
	* Method to get a hello
	* @return object with data
	*/
	/*function &getData()	{
		// Load the data
		if (empty( $this->_data )) {
			echo "RONG--".$this->_id;
			$query = ' SELECT * FROM #__hello '.
			' WHERE id = '.'1';
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			echo "RONG 1";
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->greeting = null;
		}
		return $this->_data;
	}*/
	
	/**
	* Retrieves the hello data
	* @return array Array of objects containing the data from the
	database
	*/
	function getData() {
		// Lets load the data if it doesn't already exist
		if (empty( $this->_data ))
		{
		$query = $this->_buildQuery();
		$this->_data = $this->_getList( $query );
		}
		return $this->_data;
	}
}